﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Specialized;
using System.Collections.Generic;
using m.Alipay;

/// <summary>
/// 功能：页面跳转同步通知页面
/// 版本：3.3
/// 日期：2012-07-10
/// 说明：
/// 以下代码只是为了方便商户测试而提供的样例代码，商户可以根据自己网站的需要，按照技术文档编写,并非一定要使用该代码。
/// 该代码仅供学习和研究支付宝接口使用，只是提供一个参考。
/// 
/// ///////////////////////页面功能说明///////////////////////
/// 该页面可在本机电脑测试
/// 可放入HTML等美化页面的代码、商户业务逻辑程序代码
/// 该页面可以使用ASP.NET开发工具调试，也可以使用写文本函数LogResult进行调试
/// </summary>
public partial class call_back_url : msBsc.Cls.mbPage
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Dictionary<string, string> sPara = GetRequestGet();
        string strAlipayInfo = string.Empty;
        string out_trade_no = string.Empty;

        if (sPara.Count > 0)//判断是否有带返回参数
        {
            Notify aliNotify = new Notify();
            bool verifyResult = aliNotify.VerifyReturn(sPara, Request.QueryString["sign"]);

            if (verifyResult)//验证成功
            {
                /////////////////////////////////////////////////////////////////////////////////////////////////////////////
                //请在这里加上商户的业务逻辑程序代码


                //——请根据您的业务逻辑来编写程序（以下代码仅作参考）——
                //获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表

                //商户订单号
                out_trade_no = Request.QueryString["out_trade_no"];

                //支付宝交易号
                string trade_no = Request.QueryString["trade_no"];

                //交易状态
                string result = Request.QueryString["result"];

                if (result == "success")
                {
                    System.Transactions.TransactionOptions transactionOption = new System.Transactions.TransactionOptions();
                    transactionOption.IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted;
                    transactionOption.Timeout = new TimeSpan(0, 10, 0);
                    using (System.Transactions.TransactionScope ts = new System.Transactions.TransactionScope(System.Transactions.TransactionScopeOption.Required, transactionOption))
                    {
                        using (msBsc.AppLogic.DataAlc.CBizDjkChargeTradingLog objCBizDjkChargeTradingLog = new msBsc.AppLogic.DataAlc.CBizDjkChargeTradingLog())
                        {
                            strAlipayInfo = objCBizDjkChargeTradingLog.doSavemAlipay(trade_no, out_trade_no);
                        }
                        ts.Complete();
                    }
                }
            }
            else//验证失败
            {
                strAlipayInfo = "支付宝返回参数验证失败";
            }

            ShowPayInfo(out_trade_no, strAlipayInfo);
        }
        //else
        //{
        //    Response.Write("无返回参数");
        //}
    }

    public string strInfoTitle = "";
    public string strOrderNo = "";
    public string strOrderNme = "";
    public string strPaylist = "";
    public string strPayVali = "";
    private void ShowPayInfo(string order_no, string strAlipayInfo)
    {
        if (order_no == string.Empty)
        {
            strInfoTitle = "<i style=\"display: inline;float: left;margin-left: -40px;font-size: 32px;line-height: 32px;\"><img src=\"/Alipay/images/info_error_50.png\" alt=\"\" width=\"32px\" height=\"32px\"/></i> <h2 class=\"tsl\" >本次支付失败，订单号为空！</h2>";
            return;
        }
        strOrderNo = order_no;
        using (msBsc.AppLogic.DataAlc.CBizDjkChargeTradingLog objtradlog = new msBsc.AppLogic.DataAlc.CBizDjkChargeTradingLog())
        {
            DataSet dsLog = objtradlog.DataObj.QueryBySQL("SELECT TRADING_SID,TRADING_NME,TRADING_QTY=0,TRADING_AMT,TRADING_TYPE_CID,CHARGE_SRC_CID FROM DJK_CHARGE_TRADING_LOG A WHERE A.PAY_DIR='支出' AND A.TRADING_NO='" + order_no + "'");
            DataRow[] arrtem = dsLog.Tables[0].Select("TRADING_SID<>'已支付'");
            if (arrtem.Length > 0)
            {
                this.ExecJScript("$('#J_GoToEmailWeb').show();");
                this.ExecJScript("$('#J_GoToEmailWeb').attr('href','');");
                strInfoTitle = "<i style=\"display: inline;float: left;margin-left: -40px;font-size: 32px;line-height: 32px;\"><img src=\"/Alipay/images/info_error_50.png\" alt=\"\" width=\"32px\" height=\"32px\"/></i> <h2 class=\"tsl\" >本次支付失败，应付金额<span style=\"color:#c50000;\">" + arrtem[0]["TRADING_AMT"].ToString() + "</span>元！</h2>";
            }
            else if (dsLog.Tables[0].Rows.Count > 0)
            {
                strInfoTitle = "<i class=\"iconfont\"  >&#xf0156; </i> <h2 class=\"tsl\" >恭喜您、已成功支付订单！</h2>";
            }
            else
            {
                this.ExecJScript("$('#J_GoToEmailWeb').show();");
                this.ExecJScript("$('#J_GoToEmailWeb').attr('href','');");
                strInfoTitle = "<i style=\"display: inline;float: left;margin-left: -40px;font-size: 32px;line-height: 32px;\"><img src=\"/Alipay/images/info_error_50.png\" alt=\"\" width=\"32px\" height=\"32px\"/></i> <h2 class=\"tsl\" >本次支付失败，订单信息未找到！</h2>";
            }
            if (arrtem.Length > 0 && strAlipayInfo != "OK" && strAlipayInfo != string.Empty)
            {
                strPayVali = "<p><span class=\"tsl\">本次支付校验：</span> <em></em><span class=\"tsl\">" + strAlipayInfo + "</span></p>";
            }
            for (int i = 0; i < dsLog.Tables[0].Rows.Count; i++)
            {
                if (i == 0)
                {
                    strOrderNme = dsLog.Tables[0].Rows[i]["TRADING_NME"].ToString();
                }
                strPaylist += "<p><span class=\"tsl\">" + dsLog.Tables[0].Rows[i]["CHARGE_SRC_CID"].ToString() + "：</span> <em></em><span class=\"tsl\" style=\"color:#c50000;\">" + dsLog.Tables[0].Rows[i]["TRADING_AMT"].ToString() + "</span>元！" + dsLog.Tables[0].Rows[i]["TRADING_SID"].ToString() + "</p>";
                //strPaylist += " <h2 class=\"tsl\" >" + dsLog.Tables[0].Rows[i]["CHARGE_SRC_CID"].ToString() + "支付：<span>" + arrtem[0]["TRADING_AMT"].ToString() + "</span></h2>";
            }
        }
    }

    /// <summary>
    /// 获取支付宝GET过来通知消息，并以“参数名=参数值”的形式组成数组
    /// </summary>
    /// <returns>request回来的信息组成的数组</returns>
    public Dictionary<string, string> GetRequestGet()
    {
        int i = 0;
        Dictionary<string, string> sArray = new Dictionary<string, string>();
        NameValueCollection coll;
        //Load Form variables into NameValueCollection variable.
        coll = Request.QueryString;

        // Get names of all forms into a string array.
        String[] requestItem = coll.AllKeys;

        for (i = 0; i < requestItem.Length; i++)
        {
            sArray.Add(requestItem[i], Request.QueryString[requestItem[i]]);
        }

        return sArray;
    }
}
